package com.framework.wz.wutong.base;

import android.arch.lifecycle.Lifecycle;
import android.arch.lifecycle.LifecycleObserver;
import android.arch.lifecycle.LifecycleOwner;
import android.arch.lifecycle.OnLifecycleEvent;

import org.greenrobot.eventbus.EventBus;

import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;

public abstract class BasePresenter<V extends IView> implements IPresenter<V>, LifecycleObserver{

    public V mView;
    private boolean isAttachView = mView != null;
    private CompositeDisposable mCompositeDisposable;

    public boolean useEventBus(){
        return false;
    }

    @Override
    public void attachView(V mView) {
        this.mView = mView;
        mCompositeDisposable = new CompositeDisposable();
        if (mView instanceof LifecycleOwner) {
            ((LifecycleOwner)mView).getLifecycle().addObserver(this);
        }

        if (useEventBus()) {
            EventBus.getDefault().register(this);
        }
    }

    public void addSubscription(Disposable disposable) {
        mCompositeDisposable.add(disposable);
    }

    private void unDispose() {
        if (mCompositeDisposable != null) {
            mCompositeDisposable.clear();
        }
        mCompositeDisposable = null;
    }

    @Override
    public void detachView() {
        if (useEventBus()) {
            EventBus.getDefault().unregister(this);
        }
        unDispose();
        mView = null;
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    void onDestroy(LifecycleOwner owner) {
        detachView();
        owner.getLifecycle().removeObserver(this);
    }
}
